package com.star.book.controller.system;

import com.star.book.entity.User;
import com.star.book.service.IUserService;
import com.star.book.utils.UploadUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class SysUserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/sys/user")
    public String user(Model m, @RequestParam Integer id){
        User user = SysUserInfo.loginInfo();
        m.addAttribute("user",user);
        Map<String, Object> stringObjectMap = userService.userManager(id);
        Integer page = (Integer)stringObjectMap.get("page");
        m.addAttribute("page",page);
        List<User> byPage = (List<User>) stringObjectMap.get("user");
        m.addAttribute("users",byPage);
        return "system/userManager";
    }

    @GetMapping("/sys/user/edit")
    public String edit(Model m,@RequestParam Integer id){
        User user = SysUserInfo.loginInfo();
        m.addAttribute("user",user);
        User users = userService.getById(id);
        m.addAttribute("users",users);
        return "system/user/edit";
    }

    @GetMapping("/sys/user/add")
    public String add(){

        return "system/user/add";
    }
    @PostMapping("/sys/user/save")
    public String save(Model m, @RequestParam("fileName") MultipartFile file, @RequestParam Integer userId, @RequestParam String userName, @RequestParam String userPassword, @RequestParam String userTel, @RequestParam String userEmail) throws IOException {
        User user1 = SysUserInfo.loginInfo();
        m.addAttribute("user",user1);
        String imgUrlPath = upload(file);
        System.out.println("图片地址："+imgUrlPath);
        //E:\star_book\src\main\resources\static\system\img\serImg/7aa084560db943d3be8660a081a257a8.jpg
        String[] split = imgUrlPath.split("\\\\", 7);
        String url = split[6];
       url= url.replaceAll("\\\\","/");
        url = "/" + url;
        System.out.println(url);
        User user = new User();
        if(userId != null){
            user.setUserId(userId);
        }else{
            user.setUserType("0");
            user.setUserIntegral(0);
            user.setUserDel("0");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            user.setUserRegistertime(df.format(new Date()));
            user.setUserSex("0");
            user.setUserStatus("离线");
            user.setUserLoginname("路人甲");
        }
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setUserTel(userTel);
        user.setUserEmail(userEmail);
        user.setUserImgurl(url);
        userService.saveOrUpdate(user);
        User userLoginInfo = userService.getById(userId);
        m.addAttribute("users",userLoginInfo);
        if(userId != null) {
            return "system/user/edit";
        }else{
            User userss = SysUserInfo.loginInfo();
            m.addAttribute("user",userss);
            Map<String, Object> stringObjectMap = userService.userManager(0);
            Integer page = (Integer)stringObjectMap.get("page");
            m.addAttribute("page",page);
            List<User> byPage = (List<User>) stringObjectMap.get("user");
            m.addAttribute("users",byPage);
            return "system/userManager";
        }
    }

    @SneakyThrows
    public static String upload(@RequestParam("fileName") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return "上传失败，请选择文件！";
        }
        String filePath = UUID.randomUUID().toString();
        filePath = filePath.replace("-", "");
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.length() - 4, originalFilename.length());
        filePath = filePath + substring;
        System.out.println("filepath:"+filePath);
        // 存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileDir.getAbsolutePath() + "/"+filePath));
        bos.write(file.getBytes());
        bos.flush();
        bos.close();
        return fileDir.getAbsolutePath() + "/"+filePath;
    }
}
